package utils;

import com.googlecode.flyway.core.Flyway;
import com.googlecode.flyway.core.api.MigrationInfo;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.sql.DataSource;
import java.util.logging.Logger;

@Singleton
@Startup
public class DatabaseMigrator {

    private final Logger log = Logger.getLogger(DatabaseMigrator.class.getName());

    @Resource(name = "rmtPersistenceUnit", lookup = "jdbc/rmt_db_01")
    private DataSource dataSource;

    @PostConstruct
    private void onStartup() {
        if (dataSource == null) {
            log.severe("[FLYWAY] Datasource not found!");
            throw new EJBException(
                    "[FLYWAY] No datasource found to execute the db migrations!");
        }

        Flyway flyway = new Flyway();
        flyway.setInitOnMigrate(true);
        flyway.setDataSource(dataSource);
        for (MigrationInfo i : flyway.info().all()) {
            log.info("[FLYWAY] Migrate task: " + i.getVersion() + " : "
                    + i.getDescription() + " from file: " + i.getScript());
        }
        flyway.migrate();
    }

}
